<template>
  <div class="app-container">
    <el-input placeholder="请输入搜索地址" v-model="mapName" @keyup.enter.native="mapNameChange" class="input-with-select">
      <el-button slot="append" icon="el-icon-search" @click="mapNameChange"></el-button>
    </el-input>
    <div style="padding:10px 0; display: inline-block;width: 500px">当前选中：{{ mapPointName }}</div>
    <div style="padding:10px 0; display: inline-block">经纬度：{{ lnglat}}</div>
    <div id="container"></div>
    <div id="panel" @click="setPoint"></div>
  </div>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import AMapLoader from '@amap/amap-jsapi-loader'

const { proxy } = getCurrentInstance();
const emit = defineEmits();

const props = defineProps({
  marker:{
    type: Array  ,
    default: []
  },
});
const lng = ref("");
const lat = ref("");
const map = ref(null);
const mapName = ref("");
const mapPointName = ref("");
const lnglat = ref("");
const placeSearch = ref(null);
const curPoiList = ref([]);

onMounted(() => {
  window._AMapSecurityConfig = {
    securityJsCode: "2750a7d516abf30b6f7d4acf4f0caa2c",
  };
  AMapLoader.load({
    key: "f7aa84df1f3891938473e61f093f4799", // 申请好的Web端开发者Key，首次调用 load 时必填
    version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ["AMap.Scale", 'AMap.Geocoder', 'AMap.Marker','AMap.CitySearch'], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
  })
      .then((AMap) => {
        map.value = new AMap.Map("container", {
          // 设置地图容器id
          viewMode: "3D", // 是否为3D地图模式
          zoom: 15, // 初始化地图级别
          resizeEnable: true,
          center: [118.503847,36.771550], // 初始化地图中心点位置
        });
        // 根据定位显示当前城市
        // AMap.plugin('AMap.CitySearch', function () {
        //   var citySearch = new AMap.CitySearch()
        //   citySearch.getLocalCity(function (status, result) {
        //     if (status === 'complete' && result.info === 'OK') {
        //       // 查询成功，result即为当前所在城市信息
        //       var cityinfo = result.city;
        //       var citybounds = result.bounds;
        //       //地图显示当前城市
        //       map.value.setBounds(citybounds);
        //     }
        //   })
        // })
        //异步加载插件
        // 地点搜索
        AMap.plugin(["AMap.PlaceSearch"], function () {
          placeSearch.value = new AMap.PlaceSearch({
            pageSize: 5, //单页显示结果条数
            pageIndex: 1, //页码
            city: "潍坊市", //兴趣点城市
            citylimit: false, //是否强制限制在设置的城市内搜索
            map: map.value, //展现结果的地图实例
            panel: "panel", //结果列表将在此容器中进行展示。
            autoFitView: true, //是否自动调整地图视野使绘制的 Marker 点都处于视口的可见范围
          });
         // placeSearch.search(mapName.value); //使用插件搜索关键字并查看结果
        });
        // 点标记
        map.value.on("click", function (event) {
          console.log(event, 'event.obj')
          lnglat.value = `${event.lnglat.lng},${event.lnglat.lat}`
          const position = new AMap.LngLat(event.lnglat.lng, event.lnglat.lat);
          var marker = new AMap.Marker({
            icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: position,
            anchor: 'center'
          });
          map.value.clearMap();
          map.value.add(marker);
          AMap.plugin(["AMap.PlaceSearch"], () => {
            //构造地点查询类
            let placeSearch = new AMap.PlaceSearch({
              type: "商务住宅|地名地址信息|公司企业|政府机构及社会团体|生活服务|科教文化服务|住宿服务|风景名胜",
              pageSize: 3, // 单页显示结果条数
              pageIndex: 1, // 页码
              showCover: false,
              autoFitView: false // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
            });
            placeSearch.searchNearBy('', position, 200, (status, result) => {
              console.log("result", result)
              if (result.info == 'OK') {
                if (result.poiList.pageSize == 0) {
                  return;
                }
                let curPoiList = result.poiList.pois;

                let curPoint = curPoiList[0];
                mapPointName.value = curPoint.name + "附近";

                getInfoWindow(curPoint.name, curPoint.address).open(map.value, position);
              }
            });
          })
          emit("fromChild", position);
        });
        console.log(proxy.marker)
        if(proxy.marker.length > 0) {

          const marker = new AMap.Marker({
            position: proxy.marker,
          });
          //将创建的点标记添加到已有的地图实例：
          map.value.add(marker);
          map.value.setCenter(proxy.marker); //设置地图中心点
          lnglat.value = `${proxy.marker[0] },${proxy.marker[1]}`
        }


      })
      .catch((e) => {
        console.log(e);
      });
});
function getInfoWindow(title, address, tel) {
  //实例化信息窗体
  let content = [];

  content.push("地址：" + address);
  return new AMap.InfoWindow({
    isCustom: true,  //使用自定义窗体
    anchor: 'top-center',
    content: createInfoWindow(title, content.join("<br/>")),
    offset: new AMap.Pixel(15, -155)
  });
}
function createInfoWindow(title, content) {
  let info = document.createElement("div");
  info.className = "custom-info input-card content-window-card";

  //可以通过下面的方式修改自定义窗体的宽高
  info.style.width = "260px";
  // 定义顶部标题
  let top = document.createElement("div");
  let titleD = document.createElement("div");
  let closeX = document.createElement("img");
  top.className = "info-top";
  titleD.innerHTML = title;
  closeX.src = "https://webapi.amap.com/images/close2.gif";
  closeX.onclick = closeInfoWindow;

  top.appendChild(titleD);
  top.appendChild(closeX);
  info.appendChild(top);

  // 定义中部内容
  let middle = document.createElement("div");
  middle.className = "info-middle";
  middle.style.backgroundColor = 'white';
  middle.innerHTML = content;
  info.appendChild(middle);

  // 定义底部内容
  let bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.style.position = 'relative';
  bottom.style.top = '0px';
  bottom.style.margin = '0 auto';
  let sharp = document.createElement("img");
  sharp.src = "https://webapi.amap.com/images/sharp.png";
  bottom.appendChild(sharp);
  info.appendChild(bottom);
  return info;
}
function closeInfoWindow() {
  map.value.clearInfoWindow();
}
function mapNameChange() {
  //关键字查询
  map.value.clearMap();
  placeSearch.value.search(mapName.value, function (status, result) {
    //查询成功时，result 即对应匹配的 POI 信息
    console.log(result);
    if (status == 'complete') {
      curPoiList.value = result.poiList.pois;

     // let curPoint = curPoiList.value[0];

     // map.value.add(curPoint);

    } else {
      proxy.$modal.msgSuccess("未查询出结果，请换一下关键词试试");
    }
  });
}
function setPoint(e) {
  console.log("event", e);
  let target = e.target || e.srcElement;
  let parent0 = target.parentElement;
  let parent1 = parent0.parentElement;
  let parent2 = parent1.parentElement;
  let idx = target.getAttribute('data-idx') || parent0.getAttribute('data-idx') || parent1.getAttribute('data-idx') || parent2.getAttribute('data-idx');
  // console.log("data-idx", idx);
  if (idx) {
    let curPoint = curPoiList.value[idx];
    console.log(curPoint, 'curPoint')
    lnglat.value = `${curPoint.location.lng },${curPoint.location.lat}`
    mapPointName.value = curPoint.name
    var marker = new AMap.Marker({
      // icon: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
      position: [curPoint.location.lng, curPoint.location.lat],
      anchor: 'bottom-center'
    });
    map.value.clearMap();
    map.value.add(marker);
    const position = new AMap.LngLat(curPoint.location.lng, curPoint.location.lat);
    getInfoWindow(curPoint.name, curPoint.address, curPoint.tel).open(map.value, position);
    emit("fromChild", position);
  }
}

onUnmounted(() => {
  map.value?.destroy();
});
</script>

<style lang="scss" scoped>

#container{
  padding:0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}
#panel {
  position: absolute;
  background-color: white;
  max-height: 90%;
  overflow-y: auto;
  top: 180px;
  right: 50px;
  width: 280px;
}
.operate-box{
  display: flex;
  width: 560px;
  .item{
    max-width: 300px;
    &.text{
      padding-left: 20px;
      color:red;
      font-size: 13px;
      padding-top: 30px;
    }
  }

}

:deep(.content-window-card) {
  position: relative;
  box-shadow: none;
  bottom: 0;
  left: 0;
  width: auto;
  padding: 0;
  color: black !important;
}

:deep(.content-window-card) p {
  height: 2rem;
}

:deep(.custom-info) {
  border: solid 1px silver;
  color: black !important;
}

:deep(div.info-top) {
  position: relative;
  background: none repeat scroll 0 0 #F9F9F9;
  border-bottom: 1px solid #CCC;
  border-radius: 5px 5px 0 0;
}

:deep( div.info-top div) {
  display: inline-block;
  color: #333333;
  font-size: 14px;
  font-weight: bold;
  line-height: 31px;
  padding: 0 10px;
}

:deep(div.info-top img) {
  position: absolute;
  top: 10px;
  right: 10px;
  transition-duration: 0.25s;
}

:deep(div.info-top img:hover) {
  box-shadow: 0px 0px 5px #000;
}

:deep(div.info-middle) {
  font-size: 12px;
  padding: 10px 6px;
  line-height: 20px;
  min-height: 70px;
}

:deep(div.info-bottom) {
  height: 0px;
  width: 100%;
  clear: both;
  text-align: center;
}

:deep(div.info-bottom img) {
  position: relative;
  z-index: 104;
}

span {
  margin-left: 5px;
  font-size: 11px;
}

:deep(.info-middle img) {
  float: left;
  margin-right: 6px;
}







</style>
